using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Models;
using System.Collections;
using System.IO;
using System.Drawing;
using MVCWeb.Helpers;
using System.Drawing.Imaging;
using System.Web.Security;

namespace MVCWeb.Controllers
{
    public class EventController : BaseController
    {

        //
        // GET: /Event/

        public ActionResult Gallery(int id)
        {

            return View(dc.EventPictureGalleries.Where(x => x.EventId == id));
        }

        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult ManageGallery(int id)
        {
            ViewData["EventId"] = id;
            return View(dc.EventPictureGalleries.Where(x => x.EventId == id ));
        }
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult CreatePicture(int id)
        {
            ViewData["EventId"] = id;
            EventPictureGallery entity = new EventPictureGallery();
            
            return View(entity);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult CreatePicture(int id,EventPictureGallery entity, FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Gallery\gallery\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName) + file_append.ToString() + extension;
                    }

                    // need to caculate correct width and height
                    int widthMax = 500;
                    int heightMax = 480;

                    savedFileName = Path.Combine(physicPath, sFilename);
                    hpf.SaveAs(savedFileName);

                    Image fullPicture;
                    try
                    {
                        // New image size.
                        fullPicture = new Bitmap(savedFileName);
                        Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                        fullPicture.Dispose();

                        // Delete original image.
                        if (System.IO.File.Exists(savedFileName))
                        {
                            System.IO.File.Delete(savedFileName);
                        }

                        string ext = hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                        switch (ext.ToLower())
                        {
                            case ".jpg":
                                original.Save(savedFileName, ImageFormat.Jpeg);
                                break;
                            case ".png":
                                original.Save(savedFileName, ImageFormat.Png);
                                break;
                            case ".gif":
                                original.Save(savedFileName, ImageFormat.Gif);
                                break;
                            case ".bmp":
                                original.Save(savedFileName, ImageFormat.Bmp);
                                break;
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in create thumbnail: " + ex.Message);
                    }
                    entity.ImagePath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                    entity.ThumbnailPath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }
                
                entity.EventId = id;
                
                this.dc.EventPictureGalleries.InsertOnSubmit(entity);
                this.dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("ManageGallery", new { id = id});
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
            }
            catch
            {
                EventPictureGallery eventPicture = new EventPictureGallery();
                return View(eventPicture);
            }
        }

        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult EditPicture(int id)
        {
            ViewData["EventId"] = id;
            EventPictureGallery entity = dc.EventPictureGalleries.First(x => x.GalleryId == id);
            return View(entity);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult EditPicture(int id,EventPictureGallery entity, FormCollection collection)
        {
            try
            {
                EventPictureGallery dbentity = dc.EventPictureGalleries.First(x => x.GalleryId == id);

                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Gallery\gallery\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    FileInfo oldFile = new FileInfo(dbentity.ImagePath);
                    if (oldFile.Exists)
                    {
                        oldFile.Delete();
                    } 

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName) + file_append.ToString() + extension;
                    }

                    // need to caculate correct width and height
                    int widthMax = 500;
                    int heightMax = 480;

                    savedFileName = Path.Combine(physicPath, sFilename);
                    hpf.SaveAs(savedFileName);

                    Image fullPicture;
                    try
                    {
                        // New image size.
                        fullPicture = new Bitmap(savedFileName);
                        Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                        fullPicture.Dispose();

                        // Delete original image.
                        if (System.IO.File.Exists(savedFileName))
                        {
                            System.IO.File.Delete(savedFileName);
                        }

                        string ext = hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                        switch (ext.ToLower())
                        {
                            case ".jpg":
                                original.Save(savedFileName, ImageFormat.Jpeg);
                                break;
                            case ".png":
                                original.Save(savedFileName, ImageFormat.Png);
                                break;
                            case ".gif":
                                original.Save(savedFileName, ImageFormat.Gif);
                                break;
                            case ".bmp":
                                original.Save(savedFileName, ImageFormat.Bmp);
                                break;
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in create thumbnail: " + ex.Message);
                    }
                    dbentity.ImagePath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                    dbentity.ThumbnailPath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }

                dbentity.Caption = entity.Caption;                

                this.dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("ManageGallery", new { id = dbentity.EventId });
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
            }
            catch
            {
                EventPictureGallery eventPicture = new EventPictureGallery();
                return View(eventPicture);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult DeletePicture(int id)
        {
            EventPictureGallery entity = dc.EventPictureGalleries.First(x => x.GalleryId == id);
            FileInfo oldFile = new FileInfo(entity.ImagePath);
            if (oldFile.Exists)
            {
                oldFile.Delete();
            } 
            dc.EventPictureGalleries.DeleteOnSubmit(entity);
            dc.SubmitChanges();
            return View();
        }

        [Authorize]
        public ActionResult EventList()
        {
            int communityId = 0;
            try
            {
                Community community;
                MVCWeb.Models.User user = new MVCWeb.Models.User();
                try
                {
                    MembershipUser membershipUser = Membership.GetUser();
                    Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
                    user = dc.Users.Where<MVCWeb.Models.User>(u => u.MembershipId == membershipId).First<MVCWeb.Models.User>();
                    community = dc.Communities.First<Community>(c => c.UserId == user.UserId || c.ManagerId == user.UserId);
                    communityId = community.CommunityId;
                    ViewData["CommunityId"] = communityId;
                }
                catch
                {
                    UsersInCommunity userInCommunity = dc.UsersInCommunities.First(x => x.UserId == user.UserId);
                    community = dc.Communities.First(x => x.CommunityId == userInCommunity.CommunityId);
                    communityId = community.CommunityId;
                    ViewData["CommunityId"] = communityId;
                }
            }
            catch { }
            ViewData["CurrentView"] = "Community's Event List";
            return View(dc.Events.Where(x => x.CommunityId.Value == communityId).ToList());
        }

        //
        // GET: /Event/
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Index()
        {
            if (Session["CommunityId"] == null)
            {
                return RedirectToAction("Index", "SelectCommunity", new { returnUrl = Request.RawUrl });
            }

            int communityId = Convert.ToInt32(Session["CommunityId"]);
            ViewData["CommunityId"] = communityId;

            return View(dc.Events.Where(x => x.CommunityId.Value == communityId).ToList<Event>());
        }

        //
        // GET: /Event/Details/5
        [Authorize]
        public ActionResult Details(int id)
        {
            return View(dc.Events.First(x => x.EventId == id));
        }

        //
        // GET: /Event/Create
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Create()
        {
            if (Session["CommunityId"] == null)
            {
                return RedirectToAction("Index", "SelectCommunity", new { returnUrl = Request.RawUrl });
            }

            int communityId = Convert.ToInt32(Session["CommunityId"]);
            ViewData["CommunityId"] = communityId;

            var types = from e in this.dc.Events
                        group e by e.EventType into g
                        select g.First();
            ViewData["EventTypes"] = new SelectList(types.ToList<Event>(), "EventType", "EventType");
            Event eventToCreate = new Event();
            return View(eventToCreate);
        } 

        //
        // POST: /Event/Create

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Create(Event eventToCreate, FormCollection collection)
        {
            try
            {
                int communityId = Convert.ToInt32(Session["CommunityId"]);
                eventToCreate.CommunityId = communityId;

                if (!String.IsNullOrEmpty(collection["NewEventType"]))
                {
                    eventToCreate.EventType = collection["NewEventType"];
                }
                dc.Events.InsertOnSubmit(eventToCreate);
                dc.SubmitChanges();

                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Event/Edit/5
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Edit(int id)
        {
            if (Session["CommunityId"] == null)
            {
                return RedirectToAction("Index", "SelectCommunity", new { returnUrl = Request.RawUrl });
            }

            int communityId = Convert.ToInt32(Session["CommunityId"]);
            ViewData["CommunityId"] = communityId;

            Event eventToEdit = dc.Events.First(x => x.EventId == id);

            var types = from e in this.dc.Events
                        group e by e.EventType into g
                        select g.First();
            ViewData["EventTypes"] = new SelectList(types.ToList<Event>(), "EventType", "EventType", eventToEdit.EventType);                       
            
            return View(eventToEdit);

            
        }

        //
        // POST: /Event/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Edit(int id,Event eventToEdit, FormCollection collection)
        {
            try
            {
                Event dbEvent = dc.Events.First(x => x.EventId == id);

                if (!String.IsNullOrEmpty(collection["NewEventType"]))
                {
                    eventToEdit.EventType = collection["NewEventType"];
                }

                dbEvent.EventType = eventToEdit.EventType;
                dbEvent.Active = eventToEdit.Active;
                dbEvent.Name = eventToEdit.Name;
                dbEvent.MustNotify = eventToEdit.MustNotify;
                dbEvent.EventDate = eventToEdit.EventDate;

                dc.SubmitChanges();

                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
                 
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult EventAttendant(int id)
        {
            //if (Session["CommunityId"] == null)
            //{
            //    return RedirectToAction("Index", "SelectCommunity", new { returnUrl = Request.RawUrl });
            //}

            //int communityId = Convert.ToInt32(Session["CommunityId"]);
            //ViewData["CommunityId"] = communityId;

            IList<EventAttendant> eventAttendants = dc.EventAttendants.Where(x => x.EventId == id).ToList<EventAttendant>();
            ArrayList users = new ArrayList();
            foreach (var item in eventAttendants)
            {
                User user = dc.Users.Single(x => x.UserId == item.AttendentUserId);
                users.Add(user.UserId);
            }
            
            ViewData["AttenderUsers"] = new MultiSelectList(dc.Users.ToList<User>(), "UserId", "LogInID", users);

            return View();
            
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult EventAttendant(int id, FormCollection collection)
        {
            try
            {
                string[] attenderUsers = collection["AttenderUsers"].Split(',');

                IList<EventAttendant> dbEventAttendant = dc.EventAttendants.Where(x => x.EventId == id).ToList<EventAttendant>();
                if (dbEventAttendant != null)
                {
                    dc.EventAttendants.DeleteAllOnSubmit(dbEventAttendant);
                    dc.SubmitChanges();
                }

                Event dbEvent = dc.Events.Single(x => x.EventId == id);

                IList<EventAttendant> eventAttendants = new List<EventAttendant>();
                if (attenderUsers != null)
                {
                    foreach (var item in attenderUsers)
	                {
                        int userId = Convert.ToInt32(item);
                        EventAttendant eventAttendant = new EventAttendant();
                        eventAttendant.EventId = id;
                        eventAttendant.AttendentUserId = userId;
                        eventAttendants.Add(eventAttendant);
                        
                        // Send mail to notify to event attenders.
                        try
                        {
                            Models.User user = this.dc.Users.Single(u => u.UserId == userId);
                            MembershipUser muser = Membership.GetUser(user.MembershipId);
                            string from = System.Configuration.ConfigurationManager.AppSettings["FeedbackMail"];
                            string subject = "Event Notify";
                            string body = String.Format("Hello {0}!<br /><br />Event Name : {1}<br /><br />Event Date : {2}", muser.UserName, dbEvent.Name, dbEvent.EventDate);
                            MailHelper.SendMail(from, muser.Email, "", "ngothanhtung.it@gmail.com", subject, body, System.Net.Mail.MailPriority.Normal);
                        }
                        catch 
                        { 
                        }
	                }                    
                }

                dc.EventAttendants.InsertAllOnSubmit(eventAttendants);
                dc.SubmitChanges();

                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }

            }
            catch
            {
                IList<EventAttendant> eventAttendant = dc.EventAttendants.Where(x => x.EventId == id).ToList<EventAttendant>();
                ArrayList users = new ArrayList();
                foreach (var item in eventAttendant)
                {
                    User user = dc.Users.Single(x => x.UserId == item.AttendentUserId);
                    users.Add(user.UserId);
                }
                ViewData["AttenderUsers"] = new MultiSelectList(dc.Users.ToList<User>(), "UserId", "LogInID", users);
                return View();
            }
        }

        // Only Administrators can delete event.
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            try
            {
                Event e = dc.Events.First(x => x.EventId == id);
                dc.Events.DeleteOnSubmit(e);
                dc.SubmitChanges();
                return RedirectToAction("Index", "Event");
            }
            catch
            {
                return RedirectToAction("Index", "Event");
            }
        }
    }
}
